package com.example.dell.library.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

import android.support.v7.widget.RecyclerView;

import com.example.dell.library.R;
import com.example.dell.library.adapter.BookAdapter;
import com.example.dell.library.bean.Book;

public class HomeFragment extends Fragment {
    private List<Book> bookList = new ArrayList<>();
    private RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        res();
    }

    @Override
    public void onStart() {
        super.onStart();
        res();
    }

    private void res() {
        recyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view);
        BmobQuery<Book> query = new BmobQuery<>();
        query.addWhereEqualTo("isInIt", true);
        query.findObjects(new FindListener<Book>() {
            @Override
            public void done(List<Book> list, BmobException e) {
                if (e == null) {
                    for (int i = 0; i < list.size(); i++) {
                        Boolean isInIt = list.get(i).getInIt();
                        BmobFile imgFile = list.get(i).getImgFile();
                        String name = list.get(i).getName();
                        Book book = new Book(name, imgFile, isInIt);
                        bookList.add(book);
                    }
                    GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
                    recyclerView.setLayoutManager(layoutManager);
                    BookAdapter adapter = new BookAdapter(list);
                    recyclerView.setAdapter(adapter);
                }
            }
        });
    }
}
